package com.jfirer.validator.descriptor;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.validation.Valid;
import javax.validation.metadata.ConstraintDescriptor;
import javax.validation.metadata.GroupConversionDescriptor;
import javax.validation.metadata.ReturnValueDescriptor;

public class ReturnValueDescriptorImpl extends CascadableDescriptorImpl implements ReturnValueDescriptor
{
    
    public ReturnValueDescriptorImpl(AccessibleObject accessibleObject, Set<ConstraintDescriptor<?>> constraintDescriptors)
    {
        if (accessibleObject instanceof Method)
        {
            Method method = (Method) accessibleObject;
            if (method.getReturnType() == Void.class || method.getReturnType() == void.class)
            {
                initializeCascadableDescriptor(false, new HashSet<GroupConversionDescriptor>());
                initializeElementDescriptor(method.getReturnType(), new HashSet<ConstraintDescriptor<?>>());
                return;
            }
            initializeCascadableDescriptor(method.isAnnotationPresent(Valid.class), defineGroupConversions(method.getAnnotations()));
            initializeElementDescriptor(method.getReturnType(), Collections.unmodifiableSet(constraintDescriptors));
        }
        else if (accessibleObject instanceof Constructor<?>)
        {
            Constructor<?> constructor = (Constructor<?>) accessibleObject;
            initializeCascadableDescriptor(constructor.isAnnotationPresent(Valid.class), defineGroupConversions(constructor.getAnnotations()));
            initializeElementDescriptor(constructor.getDeclaringClass(), Collections.unmodifiableSet(constraintDescriptors));
        }
        else
        {
            throw new IllegalArgumentException();
        }
    }
    
}
